package com.upcode.weighing.detect.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.upcode.weighing.base.controller.BaseController;
import com.upcode.weighing.detect.service.DetectRecordService;
import com.upcode.weighing.domain.DetectRecord;
import com.upcode.weighing.domain.DriverInfo;
import com.upcode.weighing.log.OpsLog;
import com.upcode.weighing.service.DriverInfoService;
import com.upcode.weighing.vo.req.DetectRecordAddVo;
import com.upcode.weighing.vo.req.DetectRecordEditVo;
import com.upcode.weighing.vo.req.DetectRecordQueryParam;
import com.upcode.weighing.vo.req.PageReqVo;
import com.upcode.weighing.vo.resp.BaseResponseVo;
import com.upcode.weighing.vo.resp.DetectRecordRespVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author alex
 * @since 2024-07-21
 */
@Controller
@RequestMapping("/detectrecord")
@Api(value = "/detectrecord",description = "检测记录接口",produces = MediaType.ALL_VALUE,tags = {"检测记录接口"})
public class DetectRecordController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(DetectRecordController.class);
    @Autowired
    private DetectRecordService detectRecordService;

    @Autowired
    private DriverInfoService driverInfoService;
    /**
     * 添加检测记录
     */
    @OpsLog(operation = "检测记录接口/添加检测记录" ,type = 2)
    @PostMapping("/add")
    @ApiOperation(value = "添加检测记录", notes = "添加", httpMethod = "POST")
    public Object add(@Validated @RequestBody DetectRecordAddVo detectRecordAddVo) {
        DetectRecord detectRecord=new DetectRecord();
        BeanUtils.copyProperties(detectRecordAddVo,detectRecord);
        Long recordId=IdWorker.getId();
        detectRecord.setId(recordId);
        //设置车型
        if(detectRecord.getAxleNumber()==2 ){
            if(detectRecord.getPlateColor()==0){
                detectRecord.setVehicleType(12);//2轴蓝
            }else{
                detectRecord.setVehicleType(detectRecord.getAxleNumber());
            }
        }else if(detectRecord.getAxleNumber()<=6){
            detectRecord.setVehicleType(detectRecord.getAxleNumber());
        }else if(detectRecord.getAxleNumber()>6){
            if(detectRecord.getTruckType().startsWith("flat_s")){
                detectRecord.setVehicleType(7);//普通平板车
            }else if(detectRecord.getTruckType().startsWith("flat_h")){
                detectRecord.setVehicleType(8);//液压平板车
            }
        }
        //设置超限类型
        if(detectRecord.getOverWeight().doubleValue()>0 && detectRecord.getAxisOverWeight().doubleValue()>0){
            detectRecord.setOverType(4);//总重轴荷超限
        }else if(detectRecord.getOverWeight().doubleValue()>0 ){
            detectRecord.setOverType(2);//总重超限
        }else if(detectRecord.getAxisOverWeight().doubleValue()>0){
            detectRecord.setOverType(3);//轴荷超限
        }else{
            detectRecord.setOverType(1);//未超限
        }
        try{
            detectRecordService.saveOrUpdate(detectRecord);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return error(e.getMessage());
        }

        return success(recordId);
    }
    /**
     * 获取检测记录分页列表
     */
    @OpsLog(operation = "检测记录接口/分页查询" ,type = 1)
    @PostMapping("/queryPage")
    @ApiOperation(value = "检测记录分页查询",notes = "")
    public ResponseEntity<BaseResponseVo<IPage<DetectRecordRespVo>>> queryPage(@RequestBody PageReqVo<DetectRecordQueryParam> queryParamPageReqVo){
        IPage<DetectRecordRespVo> page = detectRecordService.queryPageList(queryParamPageReqVo);
        return HttpResponse.success(page);
    }


    /**
     * 获取检测记录分页列表
     */
    @OpsLog(operation = "检测记录接口/超限分页查询" ,type = 1)
    @PostMapping("/queryOverPage")
    @ApiOperation(value = "检测记录分页查询",notes = "")
    public ResponseEntity<BaseResponseVo<IPage<DetectRecordRespVo>>> queryOverPage(@RequestBody PageReqVo<DetectRecordQueryParam> queryParamPageReqVo){
        IPage<DetectRecordRespVo> page = detectRecordService.queryOverPage(queryParamPageReqVo);
        return HttpResponse.success(page);
    }

    /**
     *
     *检测记录详情
     */
    @GetMapping("/detail/{id}")
    @ApiOperation(value = "检测记录接口/查看详情" , notes = "")
    public ResponseEntity<BaseResponseVo<DetectRecordRespVo>> details(@PathVariable("id")@NotNull(message = "id 不能为空") Long userId){
        DetectRecord detectRecord = detectRecordService.getById(userId);
        DetectRecordRespVo detectRecordRespVo=new DetectRecordRespVo();
        BeanUtils.copyProperties(detectRecord,detectRecordRespVo);
        detectRecordRespVo.setTruckPhoto(detectRecord.getTruckPhoto()+"");
        detectRecordRespVo.setPlatePhoto(detectRecord.getPlatePhoto()+"");
        detectRecordRespVo.setTruckVedio(detectRecord.getTruckVedio()+"");
        List<String> images=new ArrayList<>();
        if(photoIdToStr(detectRecord.getTruckPhoto())!=null){
            images.add(photoIdToStr(detectRecord.getTruckPhoto()));
        }
        if(detectRecord.getDriverId()!=null && detectRecord.getDriverId()>0){
            DriverInfo driverInfo = driverInfoService.getById(detectRecord.getDriverId());
            detectRecordRespVo.setDriverName(driverInfo.getDriverName());
            detectRecordRespVo.setDriverIdNo(driverInfo.getDriverIdNo());
            detectRecordRespVo.setDriverSex(driverInfo.getDriverSex());
            detectRecordRespVo.setDrivingLicenseNo(driverInfo.getDrivingLicenseNo());
            detectRecordRespVo.setVehicleRecognizeNo(driverInfo.getVehicleRecognizeNo());
            detectRecordRespVo.setDriverIdPhoto(driverInfo.getDriverIdPhoto()+"");
            detectRecordRespVo.setDrivingLicensePhoto(driverInfo.getDrivingLicensePhoto()+"");
            detectRecordRespVo.setVehicleRecognizePhoto(driverInfo.getVehicleRecognizePhoto()+"");
            //添加证照图片
            if(photoIdToStr(driverInfo.getDriverIdPhoto())!=null){
                images.add(photoIdToStr(driverInfo.getDriverIdPhoto()));
            }
            if(photoIdToStr(driverInfo.getDrivingLicensePhoto())!=null){
                images.add(photoIdToStr(driverInfo.getDrivingLicensePhoto()));
            }
            if(photoIdToStr(driverInfo.getVehicleRecognizePhoto())!=null){
                images.add(photoIdToStr(driverInfo.getVehicleRecognizePhoto()));
            }
        }
        if(images.size()>0){
            String imageStr=images.stream().collect(Collectors.joining(","));
            detectRecordRespVo.setDetectImages(imageStr);
        }
        return HttpResponse.success(detectRecordRespVo);
    }

    private String photoIdToStr(Long id){
        if(id!=null && id>0){
            return id+"";
        }else {
            return null;
        }
    }
    /**
     * 根据id修改信息
     */
    @OpsLog(operation = "检测记录接口/更新检测记录" ,type = 4)
    @PostMapping("/update")
    @ApiOperation(value = "更新检测记录" ,notes = "")
    public Object updateById(@Validated @RequestBody DetectRecordEditVo detectRecordEditVo){
        DetectRecord detectRecord=new DetectRecord();
        Long driverId=null;
        if(StringUtils.isNotEmpty(detectRecordEditVo.getDriverName()) || StringUtils.isNotEmpty(detectRecordEditVo.getDriverIdNo())){
            //保存驾驶人信息
            DriverInfo driverInfo=new DriverInfo();
            driverId=IdWorker.getId();
            BeanUtils.copyProperties(detectRecordEditVo,driverInfo);
            driverInfo.setId(driverId);
            driverInfoService.saveOrUpdate(driverInfo);
        }

        BeanUtils.copyProperties(detectRecordEditVo,detectRecord);
        if(driverId!=null){
            detectRecord.setDriverId(driverId);
        }
        try {
            if(!detectRecordService.updateById(detectRecord)){
                return error("修改失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(e.getMessage());
        }
        return success("修改成功");
    }

    /**
     * 根据id修改删除
     */
    @OpsLog(operation = "删除" ,type = 4)
    @PostMapping("/delete/{id}")
    @ApiOperation(value = "检测记录删除" ,notes = "")
    public Object delete(@PathVariable("id")@NotNull(message = "id 不能为空") Long id){
        try {
            if(!detectRecordService.removeById(id)){
                return error("删除失败");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return error(e.getMessage());
        }
        return success("删除成功");
    }

    /**
     * 检测记录接口/TopN 查询
     */
    @OpsLog(operation = "检测记录接口/TopN 查询" ,type = 1)
    @GetMapping("/topn/{num}")
    @ApiOperation(value = "检测记录接口/TopN 查询",notes = "")
    public  ResponseEntity<BaseResponseVo<List<DetectRecordRespVo> >> queryPage( @PathVariable("num")@NotNull(message = "num 不能为空") Integer num){
        List<DetectRecordRespVo> detectRecordList = detectRecordService.queryTopN(num);
        return HttpResponse.success(detectRecordList);
    }
}
